<?php
namespace Wechat\Controller;

class ApiController extends \Think\Controller{
    
    public $post_data; //微信服务器发送过来的数据
    public $rule;
    public $replyobj;
    public $resultStr;
    
    public function index(){
        $token = C('TOKEN');
        if(isset($_GET['echostr']) && isset($_GET["signature"]) && isset($_GET["timestamp"]) && isset($_GET["nonce"])){
            echo $this->valid($token); //公众平台校验
        }else{
            echo $this->responseMsg();
        }
    }
    
    //解析微信post过来的数据
    private function getPostData(){
        $postObj = simplexml_load_string($GLOBALS["HTTP_RAW_POST_DATA"], 'SimpleXMLElement', LIBXML_NOCDATA);
        $data = array();
        //通用消息
        $data['FromUserName'] = trim($postObj->FromUserName);
        $data['ToUserName'] = trim($postObj->ToUserName);
        $data['FromMsgType'] = trim($postObj->MsgType);
        $data['Keyword'] = trim($postObj->Content);
        $data['CreateTime'] = trim($postObj->CreateTime);
        //图片消息
        $data['PicUrl'] = trim($postObj->PicUrl);
        //语音消息
        $data['Recognition']  = trim($postObj->Recognition);
        //地理位置消息
        $data['Location_X'] = trim($postObj->Location_X);
        $data['Location_Y'] = trim($postObj->Location_Y);
        $data['Label'] = trim($postObj->Label);
        //事件推送
        $data['Event'] = trim($postObj->Event);
        $data['EventKey'] = trim($postObj->EventKey);
        
        if($data['FromMsgType'] == 'image'){
            $data['Keyword'] = '[发送图片]';
        }elseif($data['FromMsgType'] == 'voice'){
            $data['Keyword'] = $data['Recognition'];
        }elseif($data['FromMsgType'] == 'location'){
            $data['Keyword'] = '[发送位置]'.$data['Label'];
        }elseif($data['Event'] == 'CLICK' || $data['Event'] == 'VIEW'){//菜单点击事件
            $data['Keyword'] = $data['EventKey'];
        }
        
        $data['timesign']=time().rand(1000,9999);
        return $data;
    }
    
    //回复微信
    private function responseMsg(){
        $Member = M('WxMember');
        $this->post_data = $this->getPostData();//解析微信post过来的数据
        $this->addMessage();//收消息入库
        
        //添加或更新会员
        $memberRow = $Member->where(array("fromuser"=>$this->post_data['FromUserName']))->find();
        
        $rowMem = array();
        $rowMem['fromuser']    = $this->post_data['FromUserName'];
        $rowMem['timesign']    = $this->post_data['timesign'];
        
        if(strtolower($this->post_data['Event']) == 'unsubscribe'){
            $rowMem['unsubscribe_time'] = time();
            $rowMem['status'] = '0';
        }else{
            if(strtolower($this->post_data['Event']) == 'subscribe'){
                $rowMem['subscribe_time'] = time();
                $rowMem['status'] = '1';
            }
            //非取消关注时获取用户头像昵称等信息
            if($this->post_data['FromUserName'] && empty($memberRow['nickname'])){
                $access_token = D('WxToken')->getToken(C('APPID'),C('APPSECRET'));//获取access_token
                $userInfo = D('WxApi')->getUserInfo($access_token,$this->post_data['FromUserName']);//获取用户基本信息
                if(!empty($userInfo['nickname'])){
                    $rowMem['group_id'] = $userInfo['groupid'];
                    $rowMem['nickname'] = $userInfo['nickname'];
                    $rowMem['headimgurl'] = $userInfo['headimgurl'];
                    $rowMem['sex'] = $userInfo['sex'];
                    $rowMem['language'] = $userInfo['language'];
                    $rowMem['country'] = $userInfo['country'];
                    $rowMem['province'] = $userInfo['province'];
                    $rowMem['city'] = $userInfo['city'];
                }
            }
        }
        empty($memberRow) ? $Member->add($rowMem) : $Member->where(array('id'=>$memberRow['id']))->save($rowMem);
        
        //关注+取消关注
        if(strtolower($this->post_data['Event'])=='subscribe' || strtolower($this->post_data['Event'])=='unsubscribe'){
            //插入关注记录
            $careStatus = strtolower($this->post_data['Event']) == 'subscribe' ? '1' : '0';
            M('WxCareRecord')->add(array('is_care'=>$careStatus,'fromuser'=>$this->post_data['FromUserName']));
            //关注自动回复
            $replyRow = M("WxAutoReply")->where(array('type'=>'1','state'=>'1'))->find();
            if($careStatus == '1' && $replyRow){
                if($replyRow['is_content'] == '1'){
                    return $this->create_xmlcontent('text', $replyRow['content']);
                }else{
                    $this->post_data['Keyword'] = $replyRow['keyword'];
                }
            }else{
                return false;
            }
        }
        
        if(strtolower($this->post_data['Event']) != 'location')
            $returnxml = $this->getInfo();//暂不处理自动上传地理位置的信息
        return $returnxml;
    }
    
    //获取回复内容
    public function getInfo(){
        $keywordinfo = M('WxKeyword')->where(array('keyword'=>$this->post_data['Keyword']))->find();
        if(empty($keywordinfo)){
            //无匹配回复
            if($replyRow = M("WxAutoReply")->where(array('type'=>'2','state'=>'1'))->find()){
                return $this->create_xmlcontent('text', $replyRow['content']);
            }else{
                return false;
            }
        }else{
            $data = array();
            if($keywordinfo['type'] == 'text'){
                $data = $this->getText($keywordinfo['common_id']);
            }elseif($keywordinfo['type'] == 'single'){
                $data = $this->getSingle($keywordinfo['common_id']);
            }
            return $this->create_xmlcontent($data['msgtype'], $data['content'], $data['title'], $data['description'], $data['picurl'], $data['url'], $data['bodystr']);
        }
    }
    
    //收到的消息入库
    protected function addMessage() {
        $row = array();
        $row['fromuser']    = $this->post_data['FromUserName'];
        $row['touser']      = $this->post_data['ToUserName'];
        $row['msgtype']     = $this->post_data['FromMsgType'];
        $row['msg_content'] = $this->post_data['Keyword'];
        $row['create_time'] = $this->post_data['CreateTime'];
        M('WxMessage')->add($row);
    }
    
    //文字回复
    public function getText($id){
        $WxCommon = M('WxCommon');
        $inforesult = $WxCommon->where(array('id'=>$id,'state'=>'1'))->find();
        $WxCommon->where(array('id'=>$id))->setInc('push_num');//推送量+1
        return array('msgtype'=>'text','content'=>$inforesult['content']);
    }
    
    //单图文回复
    public function getSingle($id){
        $WxCommon = M('WxCommon');
        $inforesult = $WxCommon->where(array('id'=>$id,'state'=>'1'))->find();
        $WxCommon->where(array('id'=>$id))->setInc('push_num');//推送量+1
        
        $data['msgtype']     = 'news';
        $data['title']       = $inforesult['title'];
        $data['info_intro']  = htmlspecialchars_decode($inforesult['content']);
        $data['description'] = $inforesult['des'] ? $inforesult['des'] : cut_str(delete_html($data['info_intro']), 80);
        $data['picurl']      = C('PRO_URL').trim($inforesult['pic'],'.');
        $data['url']         = $inforesult['url'];
        if(empty($data['url']))
            $data['url'] = 'http://'.$_SERVER['HTTP_HOST'].U('Admin/Wechat/single',array('id'=>$id));
        
        //外链统一带上openid
        if(strstr($data['url'],"?")){
            $data['url']=$data['url']."&fromuser=".$this->post_data['FromUserName']."&sign=".$this->post_data['CreateTime'];
        }else{
            $data['url']=$data['url']."?fromuser=".$this->post_data['FromUserName']."&sign=".$this->post_data['CreateTime'];
        }
        
        return $data;
    }
    
    /**
     * 组合xml内容 
     * @param string $msgtype text文字,news图文,music音乐
     * @param string $content 文字消息体
     * @param string $title 图文标题
     * @param string $description 图文简介
     * @param string $picurl 图文封面
     * @param string $url 图文链接
     * @param string $bodystr 已组合好的格式体，通常用在多图文中
     */
    public function create_xmlcontent($msgtype, $content='', $title='', $description='', $picurl='', $url='', $bodystr=''){
        if($msgtype == 'text'){
            $content = str_replace("\r","",$content);
            $bodystr = '<Content><![CDATA['.$content.']]></Content>';
        }elseif($msgtype == 'news'){
            $description = cut_str($description, 120);
            if ($bodystr == ''){
                $bodystr = "<ArticleCount>1</ArticleCount>
                    <Articles>
                    <item>
                    <Title><![CDATA[$title]]></Title>
                    <Description><![CDATA[$description]]></Description>
                    <PicUrl><![CDATA[$picurl]]></PicUrl>
                    <Url><![CDATA[$url]]></Url>
                    </item>
                    </Articles>";
            }
        }elseif($msgtype == 'music'){
            $bodystr = "<Music>
                <Title><![CDATA[$title]]></Title>
                <Description><![CDATA[$description]]></Description>
                <MusicUrl><![CDATA[$url]]></MusicUrl>
                <HQMusicUrl><![CDATA[$url]]></HQMusicUrl>
                </Music>";
        }
        
        $xmlcontent = "<xml>
            <ToUserName><![CDATA[".$this->post_data['FromUserName']."]]></ToUserName>
            <FromUserName><![CDATA[" . $this->post_data['ToUserName']."]]></FromUserName>
            <CreateTime>".time()."</CreateTime>
            <MsgType><![CDATA[".$msgtype."]]></MsgType>
            ".$bodystr."
            <FuncFlag>0</FuncFlag>
            </xml>";
        return $xmlcontent;
    }
    
    //公众平台校验
    private function valid($token){
        $echoStr   = $_GET["echostr"];
        $signature = $_GET["signature"];
        $timestamp = $_GET["timestamp"];
        $nonce     = $_GET["nonce"];

        $tmpArr = array($token, $timestamp, $nonce);
        sort($tmpArr,SORT_STRING);
        $tmpStr = implode($tmpArr);
        $tmpStr = sha1($tmpStr);

        if($tmpStr == $signature) return $echoStr;
    }
    
}
